package com.mhy.wxrobot;

import android.text.TextUtils;
import android.util.Log;

import com.mhy.wxrobot.message.Message;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 *
 */
 class WxChatbotClient {

    static HttpClient httpclient = new DefaultHttpClient();

    public static SendResult send1(String webhook, Message message) throws IOException {
        if (TextUtils.isEmpty(webhook)) {
            return new SendResult();
        }
        HttpPost httppost = new HttpPost(webhook);
        httppost.addHeader("Content-Type", "application/json; charset=utf-8");
        StringEntity se = new StringEntity(message.toJsonString(), "utf-8");
        httppost.setEntity(se);

        SendResult sendResult = new SendResult();
        HttpResponse response = httpclient.execute(httppost);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String result = EntityUtils.toString(response.getEntity());
            try {
                JSONObject obj = new JSONObject(result);
                Integer errcode = obj.getInt("errcode");
                sendResult.setErrorCode(errcode);
                sendResult.setErrorMsg(obj.getString("errmsg"));
                sendResult.setIsSuccess(errcode.equals(0));
            }catch (Exception ignored){
            }
        }

        return sendResult;
    }

    // HttpClient 6.0被抛弃了
    //发送JSON字符串 如果成功则返回成功标识。
    public static SendResult send(String webhook, Message Json) {
        if (TextUtils.isEmpty(webhook)) {
            return new SendResult();
        }
        String result = "";
        BufferedReader reader = null;
        SendResult sendResult = new SendResult();
        try {
            URL url = new URL(webhook);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Charset", "UTF-8");
            // 设置文件类型:
            conn.setRequestProperty("Content-Type","application/json; charset=UTF-8");
            // 设置接收类型否则返回415错误
            //conn.setRequestProperty("accept","*/*")此处为暴力方法设置接受所有类型，以此来防范返回415;
//            conn.setRequestProperty("accept","application/json");
            // 往服务器里面发送数据
                byte[] writebytes = Json.toJsonString().getBytes();
                // 设置文件长度
                conn.setRequestProperty("Content-Length", String.valueOf(writebytes.length));
                OutputStream outwritestream = conn.getOutputStream();
                outwritestream.write(Json.toJsonString().getBytes());
                outwritestream.flush();
                outwritestream.close();
                Log.d("mhyupload", "doJsonPost: conn"+conn.getResponseCode());
            if (conn.getResponseCode() == 200) {
                reader = new BufferedReader(
                        new InputStreamReader(conn.getInputStream()));
                result = reader.readLine();
                JSONObject obj = new JSONObject(result);
                Integer errcode = obj.getInt("errcode");
                sendResult.setErrorCode(errcode);
                sendResult.setErrorMsg(obj.getString("errmsg"));
                sendResult.setIsSuccess(errcode.equals(0));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sendResult;
    }
    public static SendResult sendJson(String webhook,String json) {
        if (TextUtils.isEmpty(webhook)) {
            return new SendResult();
        }
//        String webhook = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key="+token;
        // 结果值
        StringBuffer rest = new StringBuffer();
        HttpURLConnection conn = null;
        OutputStream out = null;
        BufferedReader br = null;
        SendResult sendResult = new SendResult();
        try {
            // 创建 URL
            URL restUrl = new URL(webhook);
            // 打开连接
            conn = (HttpURLConnection) restUrl.openConnection();
            // 设置请求方式为 POST
            conn.setRequestMethod("POST");
            conn.setReadTimeout(5000);
            conn.setConnectTimeout(5000);
            conn.setRequestProperty("Connection", "keep-Alive");
            // 设置接收文件类型
//            conn.setRequestProperty("Accept","application/json");
            //设置发送文件类型
            /**
             这里注意  传递JSON数据的话 就要设置
             普通参数的话 就要注释掉
             */
            conn.setRequestProperty("Content-Type", "application/json");
            // 输入 输出 都打开
            conn.setDoOutput(true);
            conn.setDoInput(true);
            //Post方式不能缓存,需手动设置为false
            conn.setUseCaches(false);
            //开始连接
            conn.connect();
            // 传递参数  流的方式
            out = conn.getOutputStream();
            out.write(json.getBytes());
            out.flush();
            // 读取数据
            if (conn.getResponseCode() == 200) {
            br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            String line = null;
            while (null != (line = br.readLine())) {
                rest.append(line);
            }
                JSONObject obj = new JSONObject(rest.toString());
                Integer errcode = obj.getInt("errcode");
                sendResult.setErrorCode(errcode);
                sendResult.setErrorMsg(obj.getString("errmsg"));
                sendResult.setIsSuccess(errcode.equals(0));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭所有通道
            try {
                if (br != null) {
                    br.close();
                }
                if (out != null) {
                    out.close();
                }
                if (conn != null) {
                    conn.disconnect();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return sendResult;
    }
}


